<template>
  <div class="box">
    <el-alert
        :title="errorMessage"
        type="warning"
        v-if="display"
        :closable="false"
        show-icon>
      </el-alert>
    <div class="head_tree" style="width: 250px;">
      <el-tree
      node-key="id"
      :data="examOptions"
      :props="defaultProps"
      :default-expanded-keys="expanded"
      @node-click="handleNodeClick">
      </el-tree>
    </div>
    <div class="chat-box">
    <header>{{experimentName}}聊天室 (在线:{{count}}人)</header>
    <div class="msg-box" ref="msg-box">
      <div v-for="(i,index) in list" :key="index" class="msg"
        :style="i.account == account?'flex-direction:row-reverse':''">
        <div class="user-head">
          <img :src="i.avatar" height="30" width="30" :title="i.avatar">
        </div>
        <div class="user-msg">
          <span :style="i.account == account?' float: right;':''" :class="i.account == account?'right':'left'">{{i.content}}</span>
        </div>
      </div>
    </div>
    <div class="input-box">
      <input type="text" ref="sendMsg" v-model="contentText" @keyup.enter="sendText()" />
      <el-button  type="info"  size="medium" class="btn" :disabled="display" :class="{['btn-active']:contentText}" @click="sendText()">发送</el-button>
    </div>
    </div>
    <div class="left-box">
      <p class="part-title" style="margin-top: 5px;">任务区</p>
       <el-card shadow="hover" style="height: 70%;">
         <div v-html="task"></div>
       </el-card>
    </div>
    <div class="data-box">
      <p class="part-title" style="margin-top: 5px;">资料下载区</p>
      <el-card shadow="hover">
         <a :href="file">
             <el-tag>资料下载</el-tag>
           </a>
      </el-card>
    </div>
    <div class="people-box">
      <p class="part-title" style="margin-top: 5px;">群成员区域</p>
      <el-card shadow="hover" style="height: 200px;overflow-y: scroll;">
       <div v-for="(i,index) in people" :key="index">
          <div class="user-name">
            <img :src="i.avatar" height="30" width="30" :title="i.avatar">
            <span >{{i.userName}}</span>
          </div>
        </div>
      </el-card>

    </div>
  </div>
</template>

<script>
  /* eslint-disable */
  export default {
    data() {
      return {
        ws: null,
        sid:'ls10086',
        count: 0,
        list: [], // 聊天记录的数组
        contentText: "" ,// input输入的值
        username:'',
        examOptions: undefined, // 课题树选项
        defaultProps: {
                  children: 'children',
                  label: 'label'
                },
        people: [],
        expanded: [],
        expandeded:'',
        teacherName:'',
        experimentName:'',
        task:'',
        file:'',
        errorMessage:'',
        display:false
      };
    },
    computed: {
      account: {
        get () { return this.$store.state.user.account },
        set (val) { this.$store.commit('user/updateAccount', val) }
      },
      avatar: {
        get () { return this.$store.state.user.avatar },
        set (val) { this.$store.commit('user/updateAvatar', val) }
      }
    },
    created() {
      this.getExperimentList()
      this.expanded = []
      this.expanded.push(this.account)
    },
    mounted() {
      // this.initWebSocket();
    },
    destroyed() {
      // 离开页面时关闭websocket连接
      this.ws.onclose(undefined);
    },
    methods: {
      // 发送聊天信息
      sendText() {
        this.$refs["sendMsg"].focus();
        if (!this.contentText) {
          return;
        }
        let params = {
          account: this.account,
          avatar: this.avatar,
          msg: this.contentText,
          count: this.count
        };
        this.ws.send(JSON.stringify(params)); //调用WebSocket send()发送信息的方法
        this.contentText = "";
        setTimeout(() => {
          this.scrollBottm();
        }, 500);
      },
      // 进入页面创建websocket连接
      initWebSocket() {
        let _this = this;
        // 判断页面有没有存在websocket连接
        if (window.WebSocket) {
          var serverHot =  window.location.hostname;
          let sid = this.sid;
          // let sid = 'ls10086';
          console.log("sid:",sid)
          // 填写本地IP地址 端口号 要与后端配置的一致！ws://localhost:8864/
          var url = 'ws://localhost:8864/socket/groupChat/' + sid+ '/' + this.account;
          let ws = new WebSocket(url);
          _this.ws = ws;
          ws.onopen = function(e) {
            console.log("成功e:",e)
            console.log("服务器连接成功: " + url);
          };
          ws.onclose = function(e) {
            console.log("失败e:",e)
            console.log("服务器连接关闭: " + url);
          };
          ws.onerror = function() {
            console.log("服务器连接出错: " + url);
          };
          ws.onmessage = function(e) {
            //接收服务器返回的数据
            let resData = JSON.parse(e.data)
            console.log("resData:",resData)
            _this.count = resData.count;
            _this.list = [
              ..._this.list,
              { account: resData.account, username: resData.username, avatar: resData.avatar, content: resData.msg }
            ];
          };
        }
      },
      // 滚动条到底部
      scrollBottm() {
          let el = this.$refs["msg-box"];
          el.scrollTop = el.scrollHeight;
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.sid = data.id
        this.list = []
        this.task = ''
        //获取群成员信息
        this.getPeopleList();
        //根据教师账号获取教师信息
        this.getTeacherInfo();
        //根据实验uuid获取实验信息
        this.getExperimentInfo();
      },
       // 判断聊天室是否开放
       queryChat () {
         this.$http({
           url: this.$http.adornUrl('/task/queryChat'),
           method: 'get',
           params: this.$http.adornParams({
            'experimentName': this.experimentName,
           })
         }).then(({data}) => {
           if (data.success) {
             this.errorMessage = ''
             this.display = false
             this.initWebSocket();
             // 获取实时任务
             this.getTask();
           } else {
             // this.$message.error(data.message)
             this.errorMessage = data.message
             console.log(" this.errorMessage,", this.errorMessage)
             this.display = true
           }
         })
       },
      // 获取实时任务
      getTask (){
        this.$http({
          url: this.$http.adornUrl('/task/queryOneTask'),
          method: 'get',
          params: this.$http.adornParams({
           'experimentName': this.experimentName,
          })
        }).then(({data}) => {
          if (data.success) {
            data.data.task =data.data.task.replaceAll('\t','')
            data.data.task =data.data.task.replaceAll('\n','')
            data.data.task =data.data.task.replaceAll('；',' ;<br/>')
            this.task = data.data.task
            this.file = data.data.file
            this.errorMessage = ''
            this.display = false
          } else {
            // this.$message.error(data.message)
            this.errorMessage = data.message
            this.display = true
          }
        })
      },
      // 获取所有的实验
      getExperimentList () {
        this.$http({
          url: this.$http.adornUrl('/course/getExperimentNode'),
            method: 'post',
            data: this.$http.adornData({
              account: this.account,
              userType: 0
            })
        }).then(({data}) => {
          if(data.success){
            this.examOptions = data.data
          } else {
            this.$message.error(data.message)
          }
        })
      },
       //根据教师账号获取教师信息
      getTeacherInfo () {
        this.$http({
          url: this.$http.adornUrl('/teacher/getTeacherInfoByAccount'),
          method: 'get',
          params: this.$http.adornParams({
           'account': this.account,
          })
        }).then(({data}) => {
          if (data.success) {
            this.teacherName = data.data.userName
          } else {
            this.$message.error(data.message)
          }
        })
      },
       //根据实验uuid获取实验信息
      getExperimentInfo () {
        this.$http({
          url: this.$http.adornUrl('/course/queryExperimentsAllByUuId'),
          method: 'get',
          params: this.$http.adornParams({
           'uuid': this.sid,
          })
        }).then(({data}) => {
          if (data.success) {
            this.experimentName = data.data.experimentName
            // 判断聊天室是否开放
            this.queryChat();
          } else {
            this.$message.error(data.message)
          }
        })
      },
      // 获取群成员列表
      getPeopleList () {
        this.$http({
          url: this.$http.adornUrl('/student/getStudentList'),
          method: 'get',
          params: this.$http.adornParams({
           'uuid': this.sid,
          })
        }).then(({data}) => {
          if (data.success) {
            this.people = data.data
          } else {
            this.people = []
            this.$message.error(data.message)
          }
        })
      },
    }
  };
</script>

<style lang="scss" scoped>
  .chat-box {
    margin-left: 220px;
    background: #fafafa;
    position: absolute;
    height: 80%;
    width: 550px;
  header {
    position: fixed;
    width: 100%;
    height: 3rem;
    background: #273471;
    max-width: 550px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-weight: bold;
    color: white;
    font-size: 1rem;
  }
  .msg-box {
    height: 80%;
    max-width: 700px;
    margin-top: 3rem;
    overflow-y: scroll;
  .msg {
    width: 95%;
    min-height: 2.5rem;
    margin: 1rem 0.5rem;
    position: relative;
    display: flex;
    justify-content: flex-start !important;
  .user-head {
    min-width: 2.5rem;
    width: 20%;
    width: 2.5rem;
    height: 2.5rem;
    border-radius: 50%;
    background: #f1f1f1;
    display: flex;
    justify-content: center;
    align-items: center;
  .head {
    width: 1.2rem;
    height: 1.2rem;
  }  }
  .user-name{
    float: left;
  }
  .user-msg {
    width: 80%;
  // position: absolute;
    word-break: break-all;
    position: relative;
    z-index: 5;
  span {
    display: inline-block;
    padding: 0.5rem 0.7rem;
    border-radius: 0.5rem;
    margin-top: 0.2rem;
    font-size: 0.88rem;
  }
  .left {
    background: white;
    animation: toLeft 0.5s ease both 1;
  }
  .right {
    background: #53a8ff;
    color: white;
    animation: toright 0.5s ease both 1;
  }
  @keyframes toLeft {
    0% {
      opacity: 0;
      transform: translateX(-10px);
    }
    100% {
      opacity: 1;
      transform: translateX(0px);
    }
  }
  @keyframes toright {
    0% {
      opacity: 0;
      transform: translateX(10px);
    }
    100% {
      opacity: 1;
      transform: translateX(0px);
    }
  }
  }
  }
  }
  .input-box {
    padding: 0 0.5rem;
    position: absolute;
    bottom: 0;
    width: 100%;
    max-width: 756px;
    height: 3.5rem;
    background: #fafafa;
    box-shadow: 0 0 5px #ccc;
    display: flex;
    justify-content: space-between;
    align-items: center;
  input {
    height: 2.3rem;
    display: inline-block;
    width: 100%;
    padding: 0.5rem;
    border: none;
    border-radius: 0.2rem;
    font-size: 0.88rem;
  }
  .btn {
    height: 2.3rem;
    min-width: 4rem;
    background: #e0e0e0;
    padding: 0.5rem;
    font-size: 0.88rem;
    color: white;
    text-align: center;
    border-radius: 0.2rem;
    margin-left: 0.5rem;
    transition: 0.5s;
  }
  .btn-active {
    background: #409eff;
  }
  }
  }
  .head_tree{
    position: absolute;
    left: 30px;
    // height: 500px;
    width: 100px;
    display: block;
    // background-color: #009900;
  }
  .left-box{
    position: absolute;
    right: 100px;
    display: block;
    width: 300px;
    height: 200px;
    // background-color: #fff4ef;
  }
  .data-box{
    position: absolute;
    margin-top: 200px;
    right:100px;
    display: block;
    width: 300px;
    height: 120px;
    // background-color: #aaaaff;
  }
  .people-box{
    position: absolute;
    margin-top: 320px;
    right: 100px;
    display: block;
    width: 300px;
    height: 350px;
    // background-color: #fff4ef;
  }
  .part-title {
      margin: 20px 0;
      color: #000;
      padding-left: 1em;
      font-size: 16px;
      position: relative;
      display: inline-block;
      width: 100%;
  }
  .part-title:before{
    content: "";
    position: absolute;
    left: 0;
    top: 4px;
    width: 3px;
    height: 1em;
    background-color: #4976e8;
  }
  .el-button--primary {
      color: #fff;
      background-color: #273471 !important;
      border-color: #273471 !important;
  }
</style>
